<template>
  <div>
    <el-dialog
      v-loading.lock="loading"
      class="base-dialog"
      :custom-class="'panna-dialog_big'"
      :append-to-body="true"
      :title="title"
      align="center"
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      @closed="closedDialog"
    >
      <el-form
        ref="formData"
        :label-width="$i18n.locale === 'en' ? '180px' : '130px'"
        :model="formData"
        :rules="formDataRules"
        status-icon
      >
        <el-row>
          <el-col :span="11">
            <el-form-item :label="supplier.supplierName" prop="supplierName">
              <el-input
                v-model="formData.supplierName"
                :disabled="readOnly"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item :label="supplier.supplyProducts" prop="supplyProduct">
              <el-input
                v-model="formData.supplyProduct"
                :disabled="readOnly"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item :label="supplier.contacts" prop="contact">
              <el-input
                v-model="formData.contact"
                :disabled="readOnly"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item :label="supplier.telephone" prop="phone">
              <el-input
                v-model="formData.phone"
                :disabled="readOnly"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item :label="supplier.contactAddress" prop="address">
              <el-input
                v-model="formData.address"
                :disabled="readOnly"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item :label="supplier.status" prop="status">
              <el-select
                v-model="formData.status"
                :placeholder="operateType.pleaseSelect"
                :disabled="readOnly"
                filterable
              >
                <el-option :label="supplier.enable" :value="1" />
                <el-option :label="supplier.disable" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item :label="supplier.bankDeposit" prop="bank">
              <el-input v-model="formData.bank" :disabled="readOnly"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item :label="supplier.bankAccount" prop="bankAccount">
              <el-input
                v-model="formData.bankAccount"
                :disabled="readOnly"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item :label="supplier.remarks" prop="remark">
              <el-input
                v-model="formData.remark"
                type="textarea"
                :disabled="readOnly"
                maxlength="200"
                show-word-limit
                :rows="2"
                :placeholder="supplier.enterContent"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col v-if="readOnly" :span="11">
            <el-form-item :label="supplier.creationTime">
              <el-input v-model="createTime" :disabled="readOnly"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item prop="remark">
              <template v-slot:label>
                <span>{{ supplier.qualificationDocuments }}</span>
                <el-button
                  slot="trigger"
                  :disabled="readOnly"
                  size="small"
                  type="primary"
                  @click="choiseFile()"
                  >{{ supplier.uploadFiles }}</el-button
                >
              </template>
              <el-upload
                ref="upload"
                style="display: none"
                class="base-upload"
                name="FilePath"
                :multiple="true"
                action
                :headers="headers"
                :show-file-list="false"
                :accept="accept"
                :before-upload="beforeUpload"
                :on-change="upload"
                :limit="limit"
                :auto-upload="false"
                :file-list="fileList"
                :on-exceed="handleExceed"
              >
              </el-upload>
              <el-table
                ref="table"
                v-loading="tableLoading"
                :data="formData.fileWarehouse"
                style="width: 100%"
                height="200px"
              >
                <el-table-column
                  prop="originalFileName"
                  :label="supplier.fileName"
                ></el-table-column>
                <el-table-column :label="operateType.action" width="140">
                  <template slot-scope="{ row }">
                    <div class="base-table-operation">
                      <el-link type="primary" @click="downLoadUnit(row)">{{
                        operateType.download
                      }}</el-link
                      >&nbsp;&nbsp;&nbsp;&nbsp;
                      <el-link type="primary" @click="selectUnit(row)">{{
                        operateType.view
                      }}</el-link
                      >&nbsp;&nbsp;&nbsp;&nbsp;
                      <el-link
                        type="danger"
                        :disabled="readOnly"
                        @click="deleteUnit(row)"
                        >{{ operateType.delete }}</el-link
                      >
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-col>
        </el-row>
        <div>
          <span style="color: red">{{ supplier.fileFormat }}</span>
        </div>
        <div v-if="readOnly">
          <el-table
            ref="table"
            :data="formData.evaluationTable"
            style="width: 100%"
          >
            <el-table-column
              prop="num"
              :label="supplier.evaluationNumber"
            ></el-table-column>
            <el-table-column prop="opinion" :label="supplier.evaluationResults">
              <template slot-scope="scope">
                <span>{{ Opinion[scope.row.opinion] }}</span>
              </template></el-table-column
            >
            <el-table-column
              prop="score"
              :label="supplier.score"
            ></el-table-column>
            <el-table-column prop="passTime" :label="supplier.transitTime">
              <template slot-scope="scope">
                <span>{{ formatTime(scope.row.passTime) }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button
          v-if="!readOnly"
          type="primary"
          @click="onSubmit('formData')"
          >{{ operateType.save }}</el-button
        >
        <el-button @click="cancel">{{ operateType.cancel }}</el-button>
      </div>
    </el-dialog>
    <BasePreviewFile
      v-if="previewFileShow"
      :preview-file-show.sync="previewFileShow"
      :preview-file="filepreview"
    />
  </div>
</template>
<script>
import {
  get,
  create,
  update,
  LatelySupplierEvaluationGet,
  Opinion,
} from "../../../api/Supplier/Supplier.js";
import { getToken } from "@/utils/auth";
import { formdataify } from "@/utils/index";
import { WordToImage } from "@/api/Base";
import { formatTime } from "../../../utils/time";
export default {
  name: "SupplierEdit",
  components: {},
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    readOnly: {
      type: Boolean,
      default: false,
    },
    editId: {
      type: [String, Number],
      default: "",
    },
  },
  data() {
    return {
      loading: false,
      formLoading: false,
      tableLoading: false,
      dialogVisible: false,
      previewFileShow: false,
      Opinion,
      formatTime,
      fileList: [],
      filepreview: {
        storageFileName: "",
        url: "",
      },
      formLabelWidth: "110px",
      accept: ".jpg,.bmp,.png,.pdf,.doc,.docx,.xls,.xlsx",
      imgAccept: ".jpg,.bmp,.png",
      createTime: "",
      title: this.$t("Supplier.addSupplier"),
      limit: 20,
      // 业务类型
      businessType: 130,
      pageCount: 0,
      total: 0,
      headers: { Authorization: getToken() },
      formData: {
        id: 0,
        supplierName: "",
        supplyProduct: "",
        bank: "",
        bankAccount: "",
        contact: "",
        phone: "",
        address: "",
        remark: "",
        status: 1,
        evaluationState: 0,
        fileWarehouse: [],
        evaluationTable: [],
      },
      formDataRules: {
        supplierName: [
          { required: true, message: this.$t("Supplier.enterSupplierName") },
        ],
        supplyProduct: [
          { required: true, message: this.$t("Supplier.enterSuppliedProduct") },
        ],
        contact: [
          { required: true, message: this.$t("Supplier.enterContactPerson") },
        ],
        phone: [
          {
            required: true,
            message: this.$t("Supplier.enterContactPhoneNumber"),
          },
        ],
        address: [
          { required: true, message: this.$t("Supplier.enterContactAddress") },
        ],
        status: [{ required: true, message: this.$t("Supplier.selectStatus") }],
      },
    };
  },
  computed: {
    operateType() {
      return this.$t("ModuleSysBusiness.OperateType") || {};
    },
    supplier() {
      return this.$t("Supplier") || {};
    },
    hint() {
      return this.$t("ModuleSysBusiness.Hint") || {};
    },
  },
  watch: {
    value: function(newV) {
      this.title = this.editId
        ? this.readOnly
          ? this.$t("Supplier.supplierDetails")
          : this.$t("Supplier.supplierEditor")
        : this.$t("Supplier.addSupplier");
      this.dialogVisible = this.value;
      if (newV) this.init();
    },
  },
  methods: {
    // 预览
    selectUnit(row) {
      this.filepreview.fileName = row.originalFileName; // 文件名称（包括后缀名）storageFileName
      this.filepreview.storageFileName = row.storageFileName;
      this.filepreview.urlList = null;
      this.filepreview.type = "";
      this.loading = true;
      var houzui = this.filepreview.storageFileName.split(".")[1];
      houzui = houzui.toLowerCase();
      if (houzui === "docx" || houzui === "doc") {
        WordToImage({ filePath: row.filePath })
          .then((res) => {
            this.filepreview.urlList = res.data;
            this.filepreview.type = "img";
            this.loading = false;
            this.previewFileShow = true;
          })
          .catch(() => {
            this.loading = false;
          });
      } else {
        this.filepreview.url = row.filePath;
        this.loading = false;
        this.previewFileShow = true;
      }
    },
    // 下载
    downLoadUnit(row) {
      this.Base.GetStaticFileInfo(row.filePath, row.originalFileName);
    },
    // 移除
    deleteUnit(row) {
      let indexToDelete = -1;
      for (let i = 0; i < this.formData.fileWarehouse.length; i++) {
        if (this.formData.fileWarehouse[i].index === row.index) {
          indexToDelete = i;
          break;
        }
      }
      if (indexToDelete !== -1) {
        this.formData.fileWarehouse.splice(indexToDelete, 1);
        this.fileList = this.formData.fileWarehouse; // 通过创建新数组来删除元素
      }
    },
    upload(file, fileList) {
      var verify = this.beforeUpload(file);
      this.fileList = fileList;
      if (!verify) {
        this.fileList.pop();
        return false;
      }
      const obj = {
        businessType: this.businessType,
        file: file.raw,
      };
      this.tableLoading = true;
      this.$forceUpdate();
      const form = formdataify(obj);
      this.Base.uploadFileInfo(form).then((res) => {
        this.tableLoading = false;
        var testmsg = file.name.substring(file.name.lastIndexOf("."));
        const fileTypes = this.imgAccept.split(",");
        const img = fileTypes.includes(testmsg);
        var data = {
          index: this.formData.fileWarehouse
            ? this.formData.fileWarehouse.length
            : 0,
          storageFileName: res.data.newFileName,
          fileTpyeCode: 2,
          filePath: res.data.filePath,
          originalFileName: res.data.fileName,
        };
        if (img) {
          data.fileTpyeCode = 1;
        }
        this.formData.fileWarehouse.push(data);
      });
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        this.$t("Supplier.uploadLimitFunc", this.limit, files, fileList)
      );
    },
    // 上传校验 or 大小
    beforeUpload(file) {
      const fileTypes = this.accept.split(",");
      const fileExtension = file.name.substring(file.name.lastIndexOf("."));
      const checkFormat = fileTypes.includes(fileExtension.toLowerCase());

      const maxSizeInBytes = 20 * 1024 * 1024; // 20MB in bytes
      const isFileSizeValid = file.size <= maxSizeInBytes;

      if (!checkFormat) {
        this.uploadLoad = false;
        this.$message.error(this.$t("Supplier.selectFormat", this.accept));
      }

      if (!isFileSizeValid) {
        this.uploadLoad = false;
        this.$message.error(this.$t("Supplier.fileMustLess20"));
      }

      return checkFormat && isFileSizeValid;
    },
    // 上传文件
    choiseFile() {
      this.$refs["upload"].$refs["upload-inner"].handleClick();
    },
    init() {
      if (this.editId) {
        // 获取数据
        get({ id: this.editId })
          .then((res) => {
            for (let i = 0; i < res.data.fileWarehouse.length; i++) {
              res.data.fileWarehouse[i].index = i;
            }
            this.formLoading = false;
            this.formData = res.data;
            this.fileList = res.data.fileWarehouse;
            this.createTime = formatTime(this.formData.createTime);
            for (let i = 0; i < this.formData.fileWarehouse.length; i++) {
              this.formData.fileWarehouse[i].index = i;
            }
            var data = { foreignKeyId: this.editId };
            LatelySupplierEvaluationGet(data).then((res) => {
              this.formData.evaluationTable = [];
              this.formData.evaluationTable.push(res.data);
              this.$forceUpdate();
            });
          })
          .catch(() => {
            this.formLoading = false;
          });
      } else {
        this.formLoading = false;
      }
    },
    cancel() {
      this.dialogVisible = false;
    },
    // 提交表单
    onSubmit() {
      // 校验表单必填项
      this.$refs.formData.validate((valid) => {
        if (valid) {
          // 当前编辑ID是否存在 存在则去更新
          const requestData = JSON.parse(JSON.stringify(this.formData));
          if (this.editId) {
            this.editAPI(requestData);
          } else {
            // 新增
            this.addAPI(requestData);
          }
        } else {
          this.$message.error(
            this.$t("ModuleSysBusiness.Hint.provideCompleteInformation")
          );
        }
      });
    },
    // 新增接口
    addAPI(data) {
      create(data)
        .then((res) => {
          this.SuccessfulOperation();
        })
        .catch(() => {
          this.submitLoad = false;
        });
    },
    // 编辑接口
    editAPI(data) {
      update({
        ...data,
        id: this.editId,
      })
        .then((res) => {
          this.SuccessfulOperation();
        })
        .catch(() => {
          this.submitLoad = false;
        });
    },
    // 操作成功回调用
    SuccessfulOperation() {
      this.submitLoad = false;
      this.$emit("success");
      this.closedDialog();
    },
    // 关闭弹框动画结束
    closedDialog() {
      this.formData.fileWarehouse = [];
      this.fileList = [];
      // 动画结束后在清空表单 防止页面闪烁
      this.$refs.formData.resetFields();
      this.$emit("input", false);
    },
  },
};
</script>
